<?php
function middleware($handler, $stack)
{
   foreach (array_reverse($stack) as $middleware) {
      $log = function ($handler) use ($middleware) {
         return function ($name) use ($handler, $middleware) {
            $class = new $middleware();
            return $class->run($name, $handler);
         };
      };
      $handler = $log($handler);
   }
   return $handler;
}

class A
{
   public function run($a)
   {
      echo 'A:' . $a;
   }
}

class B
{
   public function run($name, $handler)
   {
      var_dump('B');
      $log = $handler($name);
      var_dump('B-');
      return $log;
   }
}

class C
{
   public function run($name, $handler)
   {
      var_dump('C');
      $log = $handler($name);
      var_dump('C-');
      return $log;
   }
}

$aa = function ($a) {
   return (new A())->run($a);
};
$stack[] = B::class;
$stack[] = C::class;
$run = middleware($aa, $stack);
$run('asd');
